import React, { useState, useRef } from 'react';
import {
  Typography,
  Container,
  Box,
  Paper,
  Card,
  CardContent,
  CardMedia,
  Button,
  LinearProgress,
  Alert,
  CircularProgress,
  Grid,
  Chip,
  Fade,
  Grow,
  Zoom,
  IconButton,
  Tooltip,
  Slider,
  Tabs,
  Tab,
  Switch,
  FormControlLabel,
  FormControl,
  Select,
  MenuItem,
} from '@mui/material';
import { styled, keyframes } from '@mui/material/styles';
import {
  CloudUpload,
  Psychology,
  Analytics,
  History,
  CheckCircle,
  Warning,
  Error as ErrorIcon,
  PhotoCamera,
  Delete,
  Refresh,
  BatchPrediction,
  PieChart
} from '@mui/icons-material';

// 动画关键帧
const fadeInUp = keyframes`
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

const pulse = keyframes`
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.7);
  }
  70% {
    transform: scale(1.05);
    box-shadow: 0 0 0 10px rgba(102, 126, 234, 0);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(102, 126, 234, 0);
  }
`;

const shimmer = keyframes`
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px + 100%) 0;
  }
`;

const glow = keyframes`
  0%, 100% {
    box-shadow: 0 0 20px rgba(102, 126, 234, 0.3);
  }
  50% {
    box-shadow: 0 0 40px rgba(102, 126, 234, 0.6);
  }
`;

const bounce = keyframes`
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
`;


const rotate = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`;

// 主容器样式
const MainContainer = styled(Container)(({ theme }) => ({
  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  minHeight: '100vh',
  paddingTop: theme.spacing(4),
  paddingBottom: theme.spacing(4),
}));

// 主要内容纸张样式
const MainPaper = styled(Paper)(({ theme }) => ({
  background: 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
  borderRadius: '24px',
  padding: theme.spacing(4),
  boxShadow: '0 20px 40px rgba(0,0,0,0.1), 0 0 0 1px rgba(255,255,255,0.05)',
  backdropFilter: 'blur(10px)',
  border: '1px solid rgba(255,255,255,0.2)',
  animation: `${fadeInUp} 0.8s ease-out`,
}));

// 标题样式
const GradientTitle = styled(Typography)(({ theme }) => ({
  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  WebkitBackgroundClip: 'text',
  WebkitTextFillColor: 'transparent',
  backgroundClip: 'text',
  fontWeight: 800,
  textAlign: 'center',
  marginBottom: theme.spacing(3),
  position: 'relative',
  '&::after': {
    content: '""',
    position: 'absolute',
    bottom: '-10px',
    left: '50%',
    transform: 'translateX(-50%)',
    width: '100px',
    height: '4px',
    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    borderRadius: '2px',
  },
}));

// 上传区域样式
const UploadZone = styled(Box)<{ isDragOver?: boolean }>(({ theme, isDragOver }) => ({
  border: `3px dashed ${isDragOver ? '#764ba2' : '#667eea'}`,
  borderRadius: '24px',
  padding: theme.spacing(4),
  minHeight: '350px',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
  cursor: 'pointer',
  background: isDragOver
    ? 'linear-gradient(145deg, #f0f4ff 0%, #e6f0ff 100%)'
    : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
  transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
  position: 'relative',
  overflow: 'hidden',
  transform: isDragOver ? 'translateY(-8px) scale(1.03)' : 'translateY(0) scale(1)',
  boxShadow: isDragOver
    ? '0 20px 60px rgba(102, 126, 234, 0.3)'
    : '0 8px 32px rgba(0,0,0,0.1)',
  '&:hover': {
    borderColor: '#764ba2',
    transform: 'translateY(-8px) scale(1.02)',
    boxShadow: '0 16px 48px rgba(102, 126, 234, 0.2)',
    animation: `${glow} 2s ease-in-out infinite`,
    '&::before': {
      opacity: 1,
    },
  },
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: '-100%',
    width: '100%',
    height: '100%',
    background: `linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.15), transparent)`,
    transition: 'left 0.6s',
    opacity: 0,
  },
  '&:hover::before': {
    left: '100%',
    opacity: 1,
  },
  '&::after': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    background: 'linear-gradient(45deg, transparent 30%, rgba(102, 126, 234, 0.05) 50%, transparent 70%)',
    opacity: 0,
    transition: 'opacity 0.3s ease',
  },
  '&:hover::after': {
    opacity: 1,
  },
}));

// 预测结果卡片样式
const ResultCard = styled(Card)(({ theme }) => ({
  height: '100%',
  background: 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
  borderRadius: '24px',
  padding: theme.spacing(3),
  border: '1px solid rgba(255,255,255,0.3)',
  boxShadow: '0 8px 32px rgba(0,0,0,0.1), 0 0 0 1px rgba(255,255,255,0.05)',
  transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
  position: 'relative',
  overflow: 'hidden',
  backdropFilter: 'blur(10px)',
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: '4px',
    background: 'linear-gradient(90deg, #FF6B6B, #4ECDC4, #45B7D1, #96CEB4)',
    borderRadius: '24px 24px 0 0',
  },
  '&::after': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: '-100%',
    width: '100%',
    height: '100%',
    background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent)',
    transition: 'left 0.6s',
  },
  '&:hover': {
    transform: 'translateY(-8px) scale(1.02)',
    boxShadow: '0 20px 50px rgba(0,0,0,0.2), 0 0 0 1px rgba(255,255,255,0.1)',
    animation: `${glow} 2s ease-in-out infinite`,
    '&::after': {
      left: '100%',
    },
  },
})) as typeof Card;

// 预测历史卡片样式
const HistoryCard = styled(Card)(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  padding: theme.spacing(2.5),
  background: 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
  borderRadius: '16px',
  border: '1px solid rgba(255,255,255,0.2)',
  boxShadow: '0 4px 16px rgba(0,0,0,0.08)',
  transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
  cursor: 'pointer',
  '&:hover': {
    transform: 'translateY(-2px) scale(1.02)',
    boxShadow: '0 8px 32px rgba(0,0,0,0.15)',
  },
})) as typeof Card;

// 现代化按钮样式
const ModernButton = styled(Button)(({ theme }) => ({
  borderRadius: '12px',
  padding: theme.spacing(1.5, 4),
  fontWeight: 600,
  textTransform: 'none',
  fontSize: '1rem',
  boxShadow: '0 4px 16px rgba(0,0,0,0.1)',
  transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
  '&:hover': {
    transform: 'translateY(-2px)',
    boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
  },
}));

// 进度条样式
const ModernProgress = styled(LinearProgress)(({ theme }) => ({
  height: '12px',
  borderRadius: '8px',
  backgroundColor: '#e2e8f0',
  boxShadow: 'inset 0 2px 4px rgba(0,0,0,0.1)',
  '& .MuiLinearProgress-bar': {
    borderRadius: '8px',
    background: 'linear-gradient(90deg, #667eea 0%, #764ba2 50%, #f093fb 100%)',
    backgroundSize: '200% 100%',
    animation: `${shimmer} 2s ease-in-out infinite`,
    boxShadow: '0 2px 8px rgba(102, 126, 234, 0.3)',
  },
}));

// 类别映射（英文到中文）
const classMapping: { [key: string]: string } = {
  'glioma': '胶质瘤(glioma)',
  'meningioma': '脑膜瘤(meningioma)',
  'notumor': '无肿瘤(notumor)',
  'pituitary': '垂体瘤(pituitary)'
};

const PredictionPage: React.FC = () => {
  // 状态管理
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [selectedImageFile, setSelectedImageFile] = useState<File | null>(null);
  const [predictionResult, setPredictionResult] = useState<any>(null);
  const [isPredicting, setIsPredicting] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [predictionHistory, setPredictionHistory] = useState<any[]>([]);
  const [isDragOver, setIsDragOver] = useState<boolean>(false);
  const [currentTab, setCurrentTab] = useState<number>(0);
  const [showHeatmap, setShowHeatmap] = useState<boolean>(false);
  const [heatmapOpacity, setHeatmapOpacity] = useState<number>(50);
  const [heatmapMode, setHeatmapMode] = useState<'overlay' | 'side'>('overlay');
  const [batchFiles, setBatchFiles] = useState<File[]>([]);
  const [batchResults, setBatchResults] = useState<any>(null);
  const [isBatchPredicting, setIsBatchPredicting] = useState<boolean>(false);
  const [showBatchHeatmap, setShowBatchHeatmap] = useState<boolean>(false);
  const [batchHeatmapOpacity, setBatchHeatmapOpacity] = useState<number>(50);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const batchInputRef = useRef<HTMLInputElement>(null);


  // 调用带热力图的预测API
  const callPredictionWithHeatmapAPI = async (imageFile: File): Promise<any> => {
    const formData = new FormData();
    formData.append('image', imageFile);

    const response = await fetch('/api/predict_with_heatmap', {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      throw new Error('HTTP error! status: ' + response.status);
    }

    const result = await response.json();

    // 转换类别名称为中文
    const topResult = {
      class: classMapping[result.predicted_class] || result.predicted_class,
      confidence: result.confidence
    };

    const allResults = result.all_probabilities.map((prob: any) => ({
      class: classMapping[prob.class] || prob.class,
      confidence: prob.confidence
    }));

    return {
      topResult,
      allResults,
      imageUrl: URL.createObjectURL(imageFile),
      heatmap: result.heatmap
    };
  };


  // 批量预测API（带热力图）
  const callBatchPredictionWithHeatmapAPI = async (files: File[]): Promise<any> => {
    const formData = new FormData();
    files.forEach(file => {
      formData.append('images', file);
    });

    const response = await fetch('/api/predict_batch_with_heatmap', {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      throw new Error('HTTP error! status: ' + response.status);
    }

    return await response.json();
  };

  // 验证并处理文件
  const validateAndProcessFile = (file: File) => {
    setError(null);

    // 检查文件类型
    if (!file.type.match('image.*')) {
      setError('请选择有效的图像文件（JPG、PNG等）');
      return false;
    }

    // 检查文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
      setError('文件大小不能超过5MB');
      return false;
    }

    // 预览选中的图像
    const imageUrl = URL.createObjectURL(file);
    setSelectedImage(imageUrl);
    setSelectedImageFile(file);

    // 重置之前的预测结果
    setPredictionResult(null);
    return true;
  };

  // 处理文件选择
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      validateAndProcessFile(file);
    }
  };

  // 处理拖拽进入
  const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(true);
  };

  // 处理拖拽离开
  const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);
  };

  // 处理拖拽悬停
  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
  };

  // 处理文件拖拽放置
  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);

    const files = e.dataTransfer.files;
    if (files && files.length > 0) {
      const file = files[0];
      validateAndProcessFile(file);
    }
  };

  // 处理图像上传和预测
  const handlePredict = async () => {
    if (!selectedImageFile) {
      setError('请先选择一张图像');
      return;
    }

    try {
      setIsPredicting(true);
      setError(null);

      // 调用带热力图的预测API
      const result = await callPredictionWithHeatmapAPI(selectedImageFile);

      // 更新预测结果
      setPredictionResult(result);

      // 添加到预测历史
      setPredictionHistory(prev => [result, ...prev.slice(0, 4)]); // 保留最近5条记录
    } catch (err) {
      setError('预测过程中发生错误，请稍后重试');
      console.error(err);
    } finally {
      setIsPredicting(false);
    }
  };

  // 处理批量文件选择
  const handleBatchFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    if (files.length > 0) {
      setBatchFiles(files);
      setError(null);
    }
  };

  // 处理批量预测
  const handleBatchPredict = async () => {
    if (batchFiles.length === 0) {
      setError('请先选择图像文件');
      return;
    }

    try {
      setIsBatchPredicting(true);
      setError(null);

      // 使用带热力图的批量预测API
      const result = await callBatchPredictionWithHeatmapAPI(batchFiles);
      setBatchResults(result);
    } catch (err) {
      setError('批量预测过程中发生错误，请稍后重试');
      console.error(err);
    } finally {
      setIsBatchPredicting(false);
    }
  };

  // 触发文件选择对话框
  const triggerFileSelect = () => {
    fileInputRef.current?.click();
  };

  return (
    <MainContainer maxWidth="xl">
      <MainPaper elevation={0}>
        <Fade in timeout={800}>
          <GradientTitle variant="h3">
            🤖 AI脑肿瘤智能诊断系统
          </GradientTitle>
        </Fade>

        <Fade in timeout={1000}>
          <Box sx={{ mb: 4 }}>
            <Tabs
              value={currentTab}
              onChange={(e, newValue) => setCurrentTab(newValue)}
              centered
              sx={{
                '& .MuiTab-root': {
                  fontWeight: 600,
                  fontSize: '1.1rem',
                  textTransform: 'none',
                  minHeight: 48,
                },
                '& .Mui-selected': {
                  color: '#667eea',
                },
                '& .MuiTabs-indicator': {
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  height: 3,
                  borderRadius: '2px',
                },
              }}
            >
              <Tab icon={<Psychology />} label="单张诊断" />
              <Tab icon={<BatchPrediction />} label="批量诊断" />
            </Tabs>
          </Box>
        </Fade>

        <Grow in timeout={1200}>
          <Box my={5}>
            {currentTab === 0 ? (
              // 单张诊断模式
              <Grid container spacing={4}>
                {/* 左侧：图像上传区域 */}
                <Grid size={{ xs: 12, lg: 6 }}>
                <Typography
                  variant="h4"
                  component="h2"
                  gutterBottom
                  sx={{
                    color: '#2d3748',
                    fontWeight: 700,
                    mb: 3,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2
                  }}
                >
                  <PhotoCamera sx={{ color: '#667eea', fontSize: 40 }} />
                  上传MRI图像
                </Typography>

                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={handleFileSelect}
                  accept="image/*"
                  style={{ display: 'none' }}
                />

                <UploadZone
                  onClick={triggerFileSelect}
                  onDragEnter={handleDragEnter}
                  onDragLeave={handleDragLeave}
                  onDragOver={handleDragOver}
                  onDrop={handleDrop}
                  isDragOver={isDragOver}
                >
                  {selectedImage ? (
                    <Zoom in timeout={500}>
                      <Box sx={{ position: 'relative', textAlign: 'center' }}>
                        <CardMedia
                          component="img"
                          image={selectedImage}
                          title="预览图像"
                          sx={{
                            maxHeight: '280px',
                            width: 'auto',
                            borderRadius: '12px',
                            boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
                            mb: 2
                          }}
                        />
                        <Box sx={{ display: 'flex', gap: 1, justifyContent: 'center' }}>
                          <Tooltip title="重新选择">
                            <IconButton
                              onClick={(e) => {
                                e.stopPropagation();
                                triggerFileSelect();
                              }}
                              sx={{
                                backgroundColor: 'rgba(102, 126, 234, 0.1)',
                                '&:hover': { backgroundColor: 'rgba(102, 126, 234, 0.2)' }
                              }}
                            >
                              <Refresh sx={{ color: '#667eea' }} />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title="清除图像">
                            <IconButton
                              onClick={(e) => {
                                e.stopPropagation();
                                setSelectedImage(null);
                                setSelectedImageFile(null);
                                setPredictionResult(null);
                              }}
                              sx={{
                                backgroundColor: 'rgba(255, 107, 107, 0.1)',
                                '&:hover': { backgroundColor: 'rgba(255, 107, 107, 0.2)' }
                              }}
                            >
                              <Delete sx={{ color: '#FF6B6B' }} />
                            </IconButton>
                          </Tooltip>
                        </Box>
                      </Box>
                    </Zoom>
                  ) : (
                    <Fade in timeout={1200}>
                      <Box sx={{ textAlign: 'center' }}>
                        <CloudUpload
                          sx={{
                            fontSize: 80,
                            color: '#667eea',
                            mb: 2,
                            animation: `${pulse} 2s infinite`
                          }}
                        />
                        <Typography
                          variant="h5"
                          align="center"
                          sx={{
                            color: isDragOver ? '#764ba2' : '#2d3748',
                            fontWeight: 600,
                            mb: 1,
                            transition: 'color 0.3s ease'
                          }}
                        >
                          {isDragOver ? '松开鼠标上传图像' : '点击上传或拖拽MRI图像'}
                        </Typography>
                        <Typography
                          variant="body1"
                          align="center"
                          sx={{
                            color: isDragOver ? '#5a67d8' : '#718096',
                            mb: 2,
                            transition: 'color 0.3s ease'
                          }}
                        >
                          {isDragOver ? '支持拖拽上传，快速便捷' : '支持 JPG、PNG 格式，文件大小不超过 5MB'}
                        </Typography>
                        <Box sx={{ display: 'flex', gap: 1, justifyContent: 'center', flexWrap: 'wrap' }}>
                          <Chip label="高精度识别" size="small" sx={{ backgroundColor: '#667eea20', color: '#667eea' }} />
                          <Chip label="实时预测" size="small" sx={{ backgroundColor: '#4ECDC420', color: '#4ECDC4' }} />
                          <Chip label="专业级AI" size="small" sx={{ backgroundColor: '#FF6B6B20', color: '#FF6B6B' }} />
                        </Box>
                      </Box>
                    </Fade>
                  )}
                </UploadZone>

                <Box sx={{ mt: 3, display: 'flex', gap: 2, flexDirection: { xs: 'column', sm: 'row' } }}>
                  <ModernButton
                    variant="outlined"
                    onClick={triggerFileSelect}
                    startIcon={<PhotoCamera />}
                    fullWidth
                    sx={{
                      borderColor: '#667eea',
                      color: '#667eea',
                      '&:hover': {
                        borderColor: '#764ba2',
                        backgroundColor: 'rgba(102, 126, 234, 0.05)'
                      }
                    }}
                  >
                    选择图像
                  </ModernButton>
                  <ModernButton
                    variant="contained"
                    onClick={handlePredict}
                    disabled={!selectedImageFile || isPredicting}
                    startIcon={isPredicting ? <CircularProgress size={20} color="inherit" /> : <Psychology />}
                    fullWidth
                    sx={{
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      '&:hover': {
                        background: 'linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%)',
                      },
                      '&:disabled': {
                        background: '#e2e8f0',
                        color: '#a0aec0'
                      }
                    }}
                  >
                    {isPredicting ? '智能分析中...' : '🚀 开始AI诊断'}
                  </ModernButton>
                </Box>

                {error && (
                  <Fade in>
                    <Alert
                      severity="error"
                      sx={{
                        mt: 2,
                        borderRadius: '12px',
                        '& .MuiAlert-icon': {
                          color: '#FF6B6B'
                        }
                      }}
                      icon={<ErrorIcon />}
                    >
                      {error}
                    </Alert>
                  </Fade>
                )}

                {isPredicting && (
                  <Fade in>
                    <Box sx={{ mt: 3 }}>
                      <ModernProgress />
                      <Typography
                        variant="body1"
                        align="center"
                        sx={{
                          mt: 2,
                          color: '#4a5568',
                          fontWeight: 500,
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          gap: 1
                        }}
                      >
                        <CircularProgress 
                          size={20} 
                          sx={{ 
                            color: '#667eea',
                            animation: `${rotate} 1s linear infinite`
                          }} 
                        />
                        <Box sx={{ 
                          background: 'linear-gradient(45deg, #667eea, #764ba2)',
                          backgroundSize: '200% 200%',
                          WebkitBackgroundClip: 'text',
                          WebkitTextFillColor: 'transparent',
                          backgroundClip: 'text',
                          animation: `${shimmer} 2s ease-in-out infinite`
                        }}>
                          AI正在深度分析图像特征，请稍候...
                        </Box>
                      </Typography>
                    </Box>
                  </Fade>
                )}
              </Grid>

              {/* 右侧：预测结果展示 */}
              <Grid size={{ xs: 12, lg: 6 }}>
                <Typography
                  variant="h4"
                  component="h2"
                  gutterBottom
                  sx={{
                    color: '#2d3748',
                    fontWeight: 700,
                    mb: 3,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2
                  }}
                >
                  <Analytics sx={{ color: '#667eea', fontSize: 40 }} />
                  诊断结果
                </Typography>

                {predictionResult ? (
                  <Fade in timeout={800}>
                    <Grid container spacing={3}>
                      {/* 热力图控制 */}
                      {predictionResult.heatmap && (
                        <Grid size={{ xs: 12 }}>
                          <ResultCard>
                            <CardContent sx={{ p: 0 }}>
                              <Box sx={{ p: 3 }}>
                                <Typography
                                  variant="h6"
                                  component="h3"
                                  sx={{
                                    color: '#2d3748',
                                    fontWeight: 700,
                                    mb: 3,
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: 1
                                  }}
                                >
                                  🔥 AI关注区域热力图分析
                                </Typography>
                                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                                  <FormControlLabel
                                    control={
                                      <Switch
                                        checked={showHeatmap}
                                        onChange={(e) => setShowHeatmap(e.target.checked)}
                                        sx={{
                                          '& .MuiSwitch-switchBase.Mui-checked': {
                                            color: '#667eea',
                                          },
                                          '& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': {
                                            backgroundColor: '#667eea',
                                          },
                                        }}
                                      />
                                    }
                                    label="显示热力图"
                                  />
                                  {showHeatmap && (
                                    <>
                                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flex: 1 }}>
                                        <Typography variant="body2" sx={{ color: '#4a5568', minWidth: '60px' }}>
                                          透明度:
                                        </Typography>
                                        <Slider
                                          value={heatmapOpacity}
                                          onChange={(e, value) => setHeatmapOpacity(value as number)}
                                          min={0}
                                          max={100}
                                          sx={{
                                            color: '#667eea',
                                            '& .MuiSlider-thumb': {
                                              backgroundColor: '#667eea',
                                            },
                                          }}
                                        />
                                        <Typography variant="body2" sx={{ color: '#4a5568', minWidth: '40px' }}>
                                          {heatmapOpacity}%
                                        </Typography>
                                      </Box>
                                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                        <Typography variant="body2" sx={{ color: '#4a5568', minWidth: '60px' }}>
                                          模式:
                                        </Typography>
                                        <FormControl size="small" sx={{ minWidth: 120 }}>
                                          <Select
                                            value={heatmapMode}
                                            onChange={(e: any) => setHeatmapMode(e.target.value as 'overlay' | 'side')}
                                            sx={{
                                              '& .MuiOutlinedInput-notchedOutline': {
                                                borderColor: '#E2E8F0',
                                              },
                                              '&:hover .MuiOutlinedInput-notchedOutline': {
                                                borderColor: '#667eea',
                                              },
                                              '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                                                borderColor: '#667eea',
                                              },
                                            }}
                                          >
                                            <MenuItem value="overlay">叠加显示</MenuItem>
                                            <MenuItem value="side">并排显示</MenuItem>
                                          </Select>
                                        </FormControl>
                                      </Box>
                                    </>
                                  )}
                                </Box>
                                {showHeatmap && (
                                  heatmapMode === 'overlay' ? (
                                    <Box sx={{ 
                                      position: 'relative', 
                                      display: 'inline-block',
                                      maxWidth: '100%',
                                      width: '100%'
                                    }}>
                                      <img
                                        src={predictionResult.imageUrl}
                                        alt="原始图像"
                                        style={{
                                          width: '100%',
                                          maxWidth: '500px',
                                          height: 'auto',
                                          objectFit: 'contain',
                                          borderRadius: '12px',
                                          boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
                                          display: 'block'
                                        }}
                                      />
                                      <img
                                        src={predictionResult.heatmap}
                                        alt="热力图"
                                        style={{
                                          position: 'absolute',
                                          top: 0,
                                          left: 0,
                                          width: '100%',
                                          maxWidth: '500px',
                                          height: 'auto',
                                          objectFit: 'contain',
                                          borderRadius: '12px',
                                          opacity: heatmapOpacity / 100,
                                          pointerEvents: 'none',
                                          mixBlendMode: 'multiply'
                                        }}
                                      />
                                    </Box>
                                  ) : (
                                    <Box sx={{ 
                                      display: 'flex', 
                                      gap: 2, 
                                      flexWrap: 'wrap',
                                      justifyContent: 'center',
                                      alignItems: 'flex-start'
                                    }}>
                                      <Box sx={{ textAlign: 'center' }}>
                                        <img
                                          src={predictionResult.imageUrl}
                                          alt="原始图像"
                                          style={{
                                            width: '100%',
                                            maxWidth: '300px',
                                            height: 'auto',
                                            objectFit: 'contain',
                                            borderRadius: '12px',
                                            boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
                                            display: 'block'
                                          }}
                                        />
                                        <Typography variant="caption" sx={{ color: '#718096', mt: 1, display: 'block' }}>
                                          原始图像
                                        </Typography>
                                      </Box>
                                      <Box sx={{ textAlign: 'center' }}>
                                        <img
                                          src={predictionResult.heatmap}
                                          alt="热力图"
                                          style={{
                                            width: '100%',
                                            maxWidth: '300px',
                                            height: 'auto',
                                            objectFit: 'contain',
                                            borderRadius: '12px',
                                            boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
                                            display: 'block',
                                            opacity: heatmapOpacity / 100
                                          }}
                                        />
                                        <Typography variant="caption" sx={{ color: '#718096', mt: 1, display: 'block' }}>
                                          AI关注区域热力图
                                        </Typography>
                                      </Box>
                                    </Box>
                                  )
                                )}
                                <Typography
                                  variant="body2"
                                  sx={{
                                    color: '#718096',
                                    mt: 2,
                                    fontStyle: 'italic'
                                  }}
                                >
                                  {showHeatmap 
                                    ? '热力图显示AI模型关注的区域，红色区域表示高关注度' 
                                    : '开启热力图可查看AI模型的决策过程'}
                                </Typography>
                              </Box>
                            </CardContent>
                          </ResultCard>
                        </Grid>
                      )}

                      <Grid size={{ xs: 12 }}>
                        <ResultCard>
                          <CardContent sx={{ p: 0 }}>
                            <Box sx={{ p: 3, textAlign: 'center' }}>
                              <Box sx={{ display: 'flex', justifyContent: 'center', mb: 2 }}>
                                {predictionResult.topResult.confidence > 80 ? (
                                  <CheckCircle sx={{ fontSize: 60, color: '#4ECDC4' }} />
                                ) : predictionResult.topResult.confidence > 50 ? (
                                  <Warning sx={{ fontSize: 60, color: '#FFD93D' }} />
                                ) : (
                                  <ErrorIcon sx={{ fontSize: 60, color: '#FF6B6B' }} />
                                )}
                              </Box>
                              <Typography
                                variant="h6"
                                sx={{
                                  color: '#4a5568',
                                  mb: 2,
                                  fontWeight: 600
                                }}
                              >
                                AI诊断结果
                              </Typography>
                              <Typography
                                variant="h3"
                                sx={{
                                  color: predictionResult.topResult.confidence > 80 ? '#4ECDC4' :
                                    predictionResult.topResult.confidence > 50 ? '#FFD93D' : '#FF6B6B',
                                  fontWeight: 800,
                                  mb: 2,
                                  animation: `${bounce} 2s infinite`,
                                  background: predictionResult.topResult.confidence > 80 ? 
                                    'linear-gradient(45deg, #4ECDC4, #45B7D1)' :
                                    predictionResult.topResult.confidence > 50 ?
                                    'linear-gradient(45deg, #FFD93D, #FFA726)' :
                                    'linear-gradient(45deg, #FF6B6B, #FF8A80)',
                                  backgroundSize: '200% 200%',
                                  WebkitBackgroundClip: 'text',
                                  WebkitTextFillColor: 'transparent',
                                  backgroundClip: 'text',
                                  textShadow: '0 0 30px rgba(0,0,0,0.3)',
                                }}
                              >
                                {predictionResult.topResult.class}
                              </Typography>
                              <Box sx={{ display: 'flex', justifyContent: 'center', mb: 2 }}>
                                <Chip
                                  label={`置信度: ${predictionResult.topResult.confidence.toFixed(1)}%`}
                                  sx={{
                                    backgroundColor: predictionResult.topResult.confidence > 80 ? '#4ECDC420' :
                                      predictionResult.topResult.confidence > 50 ? '#FFD93D20' : '#FF6B6B20',
                                    color: predictionResult.topResult.confidence > 80 ? '#4ECDC4' :
                                      predictionResult.topResult.confidence > 50 ? '#FFD93D' : '#FF6B6B',
                                    fontWeight: 700,
                                    fontSize: '1rem',
                                    height: '32px'
                                  }}
                                />
                              </Box>
                              <Typography
                                variant="body1"
                                sx={{
                                  color: '#718096',
                                  fontStyle: 'italic'
                                }}
                              >
                                {predictionResult.topResult.confidence > 90 ? '🎯 极高置信度' :
                                  predictionResult.topResult.confidence > 80 ? '✅ 高置信度' :
                                    predictionResult.topResult.confidence > 60 ? '⚠️ 中等置信度' : '❌ 低置信度'}
                              </Typography>
                            </Box>
                          </CardContent>
                        </ResultCard>
                      </Grid>

                      <Grid size={{ xs: 12 }}>
                        <ResultCard>
                          <CardContent sx={{ p: 0 }}>
                            <Box sx={{ p: 3 }}>
                              <Typography
                                variant="h6"
                                component="h3"
                                sx={{
                                  color: '#2d3748',
                                  fontWeight: 700,
                                  mb: 3,
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: 1
                                }}
                              >
                                📊 详细分析报告
                              </Typography>
                              {predictionResult.allResults.map((result: any, index: number) => (
                                <Fade in timeout={1000 + index * 200} key={index}>
                                  <Box sx={{ mb: 3 }}>
                                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                                      <Typography
                                        variant="body1"
                                        sx={{
                                          color: '#2d3748',
                                          fontWeight: 600
                                        }}
                                      >
                                        {result.class}
                                      </Typography>
                                      <Typography
                                        variant="body1"
                                        sx={{
                                          color: '#4a5568',
                                          fontWeight: 700
                                        }}
                                      >
                                        {result.confidence.toFixed(1)}%
                                      </Typography>
                                    </Box>
                                    <ModernProgress
                                      variant="determinate"
                                      value={result.confidence}
                                      sx={{
                                        '& .MuiLinearProgress-bar': {
                                          background: result.confidence > 80 ? 'linear-gradient(90deg, #4ECDC4, #45B7D1)' :
                                            result.confidence > 50 ? 'linear-gradient(90deg, #FFD93D, #FFA726)' :
                                              'linear-gradient(90deg, #FF6B6B, #FF8A80)'
                                        }
                                      }}
                                    />
                                  </Box>
                                </Fade>
                              ))}
                            </Box>
                          </CardContent>
                        </ResultCard>
                      </Grid>
                    </Grid>
                  </Fade>
                ) : (
                  <Fade in timeout={1200}>
                    <Box
                      sx={{
                        border: '2px dashed #cbd5e0',
                        borderRadius: '20px',
                        padding: 4,
                        minHeight: '400px',
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        background: 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
                        textAlign: 'center'
                      }}
                    >
                      <Analytics sx={{ fontSize: 80, color: '#cbd5e0', mb: 3 }} />
                      <Typography
                        variant="h5"
                        sx={{
                          color: '#4a5568',
                          fontWeight: 600,
                          mb: 2
                        }}
                      >
                        等待AI诊断
                      </Typography>
                      <Typography
                        variant="body1"
                        sx={{
                          color: '#718096',
                          mb: 3,
                          maxWidth: '300px'
                        }}
                      >
                        上传MRI图像并点击"开始AI诊断"按钮，我们的人工智能将为您提供专业的分析结果
                      </Typography>
                      <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', justifyContent: 'center' }}>
                        <Chip label="深度学习" size="small" sx={{ backgroundColor: '#667eea20', color: '#667eea' }} />
                        <Chip label="医学影像" size="small" sx={{ backgroundColor: '#4ECDC420', color: '#4ECDC4' }} />
                        <Chip label="智能诊断" size="small" sx={{ backgroundColor: '#FF6B6B20', color: '#FF6B6B' }} />
                      </Box>
                    </Box>
                  </Fade>
                )}
              </Grid>
            </Grid>
            ) : (
              // 批量诊断模式
              <Grid container spacing={4}>
                {/* 批量上传区域 */}
                <Grid size={{ xs: 12 }}>
                  <Typography
                    variant="h4"
                    component="h2"
                    gutterBottom
                    sx={{
                      color: '#2d3748',
                      fontWeight: 700,
                      mb: 3,
                      display: 'flex',
                      alignItems: 'center',
                      gap: 2
                    }}
                  >
                    <BatchPrediction sx={{ color: '#667eea', fontSize: 40 }} />
                    批量MRI图像诊断
                  </Typography>

                  <input
                    type="file"
                    ref={batchInputRef}
                    onChange={handleBatchFileSelect}
                    accept="image/*"
                    multiple
                    style={{ display: 'none' }}
                  />

                  <UploadZone
                    onClick={() => batchInputRef.current?.click()}
                    onDragEnter={handleDragEnter}
                    onDragLeave={handleDragLeave}
                    onDragOver={handleDragOver}
                    onDrop={handleDrop}
                    isDragOver={isDragOver}
                    sx={{ minHeight: '200px' }}
                  >
                    {batchFiles.length > 0 ? (
                      <Zoom in timeout={500}>
                        <Box sx={{ textAlign: 'center' }}>
                          <Typography variant="h6" sx={{ color: '#2d3748', mb: 2 }}>
                            已选择 {batchFiles.length} 张图像
                          </Typography>
                          <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', justifyContent: 'center' }}>
                            {batchFiles.slice(0, 6).map((file, index) => (
                              <Chip
                                key={index}
                                label={file.name}
                                size="small"
                                sx={{ backgroundColor: '#667eea20', color: '#667eea' }}
                              />
                            ))}
                            {batchFiles.length > 6 && (
                              <Chip
                                label={`+${batchFiles.length - 6} 更多`}
                                size="small"
                                sx={{ backgroundColor: '#4ECDC420', color: '#4ECDC4' }}
                              />
                            )}
                          </Box>
                        </Box>
                      </Zoom>
                    ) : (
                      <Fade in timeout={1200}>
                        <Box sx={{ textAlign: 'center' }}>
                          <CloudUpload
                            sx={{
                              fontSize: 60,
                              color: '#667eea',
                              mb: 2,
                              animation: `${pulse} 2s infinite`
                            }}
                          />
                          <Typography
                            variant="h5"
                            align="center"
                            sx={{
                              color: isDragOver ? '#764ba2' : '#2d3748',
                              fontWeight: 600,
                              mb: 1,
                              transition: 'color 0.3s ease'
                            }}
                          >
                            {isDragOver ? '松开鼠标上传图像' : '点击上传或拖拽多张MRI图像'}
                          </Typography>
                          <Typography
                            variant="body1"
                            align="center"
                            sx={{
                              color: isDragOver ? '#5a67d8' : '#718096',
                              mb: 2,
                              transition: 'color 0.3s ease'
                            }}
                          >
                            支持同时上传多张图像进行批量诊断
                          </Typography>
                        </Box>
                      </Fade>
                    )}
                  </UploadZone>

                  <Box sx={{ mt: 3, display: 'flex', gap: 2, justifyContent: 'center' }}>
                    <ModernButton
                      variant="outlined"
                      onClick={() => batchInputRef.current?.click()}
                      startIcon={<PhotoCamera />}
                      sx={{
                        borderColor: '#667eea',
                        color: '#667eea',
                        '&:hover': {
                          borderColor: '#764ba2',
                          backgroundColor: 'rgba(102, 126, 234, 0.05)'
                        }
                      }}
                    >
                      选择图像
                    </ModernButton>
                    <ModernButton
                      variant="contained"
                      onClick={handleBatchPredict}
                      disabled={batchFiles.length === 0 || isBatchPredicting}
                      startIcon={isBatchPredicting ? <CircularProgress size={20} color="inherit" /> : <BatchPrediction />}
                      sx={{
                        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                        '&:hover': {
                          background: 'linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%)',
                        },
                        '&:disabled': {
                          background: '#e2e8f0',
                          color: '#a0aec0'
                        }
                      }}
                    >
                      {isBatchPredicting ? '批量分析中...' : '🚀 开始批量诊断'}
                    </ModernButton>
                  </Box>

                  {isBatchPredicting && (
                    <Fade in>
                      <Box sx={{ mt: 3 }}>
                        <ModernProgress />
                        <Typography
                          variant="body1"
                          align="center"
                          sx={{
                            mt: 2,
                            color: '#4a5568',
                            fontWeight: 500,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            gap: 1
                          }}
                        >
                          <CircularProgress size={16} sx={{ color: '#667eea' }} />
                          AI正在批量分析 {batchFiles.length} 张图像，请稍候...
                        </Typography>
                      </Box>
                    </Fade>
                  )}
                </Grid>

                {/* 批量预测结果 */}
                {batchResults && (
                  <Grid size={{ xs: 12 }}>
                    <Fade in timeout={800}>
                      <Box>
                        <Typography
                          variant="h4"
                          component="h2"
                          gutterBottom
                          sx={{
                            color: '#2d3748',
                            fontWeight: 700,
                            mb: 3,
                            display: 'flex',
                            alignItems: 'center',
                            gap: 2
                          }}
                        >
                          <Analytics sx={{ color: '#667eea', fontSize: 40 }} />
                          批量诊断结果
                        </Typography>

                        {/* 批量热力图控制 */}
                        <ResultCard sx={{ mb: 4 }}>
                          <CardContent sx={{ p: 0 }}>
                            <Box sx={{ p: 3 }}>
                              <Typography
                                variant="h6"
                                component="h3"
                                sx={{
                                  color: '#2d3748',
                                  fontWeight: 700,
                                  mb: 3,
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: 1
                                }}
                              >
                                🔥 批量热力图分析控制
                              </Typography>
                              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                                <FormControlLabel
                                  control={
                                    <Switch
                                      checked={showBatchHeatmap}
                                      onChange={(e) => setShowBatchHeatmap(e.target.checked)}
                                      sx={{
                                        '& .MuiSwitch-switchBase.Mui-checked': {
                                          color: '#667eea',
                                        },
                                        '& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': {
                                          backgroundColor: '#667eea',
                                        },
                                      }}
                                    />
                                  }
                                  label="显示热力图"
                                />
                                {showBatchHeatmap && (
                                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flex: 1 }}>
                                    <Typography variant="body2" sx={{ color: '#4a5568', minWidth: '60px' }}>
                                      透明度:
                                    </Typography>
                                    <Slider
                                      value={batchHeatmapOpacity}
                                      onChange={(e, value) => setBatchHeatmapOpacity(value as number)}
                                      min={0}
                                      max={100}
                                      sx={{
                                        color: '#667eea',
                                        '& .MuiSlider-thumb': {
                                          backgroundColor: '#667eea',
                                        },
                                      }}
                                    />
                                    <Typography variant="body2" sx={{ color: '#4a5568', minWidth: '40px' }}>
                                      {batchHeatmapOpacity}%
                                    </Typography>
                                  </Box>
                                )}
                              </Box>
                              <Typography
                                variant="body2"
                                sx={{
                                  color: '#718096',
                                  fontStyle: 'italic'
                                }}
                              >
                                {showBatchHeatmap 
                                  ? '热力图显示AI模型对每张图像的关注区域，红色区域表示高关注度' 
                                  : '开启热力图可查看AI模型对每张图像的决策过程'}
                              </Typography>
                            </Box>
                          </CardContent>
                        </ResultCard>

                        {/* 统计概览 */}
                        <ResultCard sx={{ mb: 4 }}>
                          <CardContent sx={{ p: 0 }}>
                            <Box sx={{ p: 3 }}>
                              <Typography
                                variant="h6"
                                component="h3"
                                sx={{
                                  color: '#2d3748',
                                  fontWeight: 700,
                                  mb: 3,
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: 1
                                }}
                              >
                                <PieChart sx={{ color: '#667eea' }} />
                                诊断统计概览
                              </Typography>
                              <Grid container spacing={2}>
                                <Grid size={{ xs: 12, sm: 6, md: 3 }}>
                                  <Box sx={{ textAlign: 'center', p: 2 }}>
                                    <Typography variant="h4" sx={{ color: '#667eea', fontWeight: 800 }}>
                                      {batchResults.total_images}
                                    </Typography>
                                    <Typography variant="body2" sx={{ color: '#4a5568' }}>
                                      总图像数
                                    </Typography>
                                  </Box>
                                </Grid>
                                {Object.entries(batchResults.class_counts).map(([className, count]) => (
                                  <Grid size={{ xs: 12, sm: 6, md: 3 }} key={className}>
                                    <Box sx={{ textAlign: 'center', p: 2 }}>
                                      <Typography variant="h4" sx={{ color: '#4ECDC4', fontWeight: 800 }}>
                                        {count as number}
                                      </Typography>
                                      <Typography variant="body2" sx={{ color: '#4a5568' }}>
                                        {classMapping[className] || className}
                                      </Typography>
                                    </Box>
                                  </Grid>
                                ))}
                              </Grid>
                            </Box>
                          </CardContent>
                        </ResultCard>

                        {/* 详细结果列表 */}
                        <Grid container spacing={2}>
                          {batchResults.results.map((result: any, index: number) => (
                            <Grid size={{ xs: 12, sm: 6, md: 4 }} key={index}>
                              <Fade in timeout={1000 + index * 100}>
                                <ResultCard>
                                  <CardContent sx={{ p: 2 }}>
                                    {/* 图像和热力图显示 */}
                                    {showBatchHeatmap && result.heatmap && (
                                      <Box sx={{ position: 'relative', display: 'inline-block', mb: 2, width: '100%' }}>
                                        <img
                                          src={batchFiles[index] ? URL.createObjectURL(batchFiles[index]) : ''}
                                          alt={`原始图像 ${index + 1}`}
                                          style={{
                                            width: '100%',
                                            height: '200px',
                                            objectFit: 'contain',
                                            borderRadius: '8px',
                                            boxShadow: '0 4px 16px rgba(0,0,0,0.1)',
                                            backgroundColor: '#f8f9fa'
                                          }}
                                        />
                                        <img
                                          src={result.heatmap}
                                          alt={`热力图 ${index + 1}`}
                                          style={{
                                            position: 'absolute',
                                            top: 0,
                                            left: 0,
                                            width: '100%',
                                            height: '200px',
                                            objectFit: 'contain',
                                            borderRadius: '8px',
                                            opacity: batchHeatmapOpacity / 100,
                                            pointerEvents: 'none',
                                            mixBlendMode: 'multiply'
                                          }}
                                        />
                                      </Box>
                                    )}
                                    
                                    <Typography
                                      variant="h6"
                                      sx={{
                                        color: '#2d3748',
                                        fontWeight: 700,
                                        mb: 1
                                      }}
                                    >
                                      {classMapping[result.predicted_class] || result.predicted_class}
                                    </Typography>
                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                                      <Chip
                                        label={`${result.confidence.toFixed(1)}%`}
                                        size="small"
                                        sx={{
                                          backgroundColor: result.confidence > 80 ? '#4ECDC420' :
                                            result.confidence > 50 ? '#FFD93D20' : '#FF6B6B20',
                                          color: result.confidence > 80 ? '#4ECDC4' :
                                            result.confidence > 50 ? '#FFD93D' : '#FF6B6B',
                                          fontWeight: 600
                                        }}
                                      />
                                      {result.confidence > 80 ? (
                                        <CheckCircle sx={{ fontSize: 16, color: '#4ECDC4' }} />
                                      ) : result.confidence > 50 ? (
                                        <Warning sx={{ fontSize: 16, color: '#FFD93D' }} />
                                      ) : (
                                        <ErrorIcon sx={{ fontSize: 16, color: '#FF6B6B' }} />
                                      )}
                                    </Box>
                                    <Typography
                                      variant="caption"
                                      sx={{
                                        color: '#718096',
                                        fontStyle: 'italic'
                                      }}
                                    >
                                      图像 #{index + 1}
                                      {showBatchHeatmap && result.heatmap && ' • 含热力图'}
                                    </Typography>
                                  </CardContent>
                                </ResultCard>
                              </Fade>
                            </Grid>
                          ))}
                        </Grid>
                      </Box>
                    </Fade>
                  </Grid>
                )}
              </Grid>
            )}
          </Box>
        </Grow>

        {/* 预测历史记录 */}
        <Fade in timeout={1600}>
          <Box my={5}>
            <Typography
              variant="h4"
              component="h2"
              gutterBottom
              sx={{
                color: '#2d3748',
                fontWeight: 700,
                mb: 4,
                display: 'flex',
                alignItems: 'center',
                gap: 2
              }}
            >
              <History sx={{ color: '#667eea', fontSize: 40 }} />
              诊断历史记录
            </Typography>

            {predictionHistory.length > 0 ? (
              <Grid container spacing={3}>
                {predictionHistory.map((historyItem, index) => (
                  <Grid size={{ xs: 12, sm: 6, lg: 4 }} key={index}>
                    <Fade in timeout={1800 + index * 200}>
                      <HistoryCard>
                        <CardMedia
                          component="img"
                          image={historyItem.imageUrl}
                          title="历史图像"
                          sx={{
                            width: 80,
                            height: 80,
                            borderRadius: '12px',
                            mr: 2,
                            boxShadow: '0 4px 16px rgba(0,0,0,0.1)'
                          }}
                        />
                        <Box sx={{ flex: 1 }}>
                          <Typography
                            variant="h6"
                            sx={{
                              color: '#2d3748',
                              fontWeight: 700,
                              mb: 0.5
                            }}
                          >
                            {historyItem.topResult.class}
                          </Typography>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                            <Chip
                              label={`${historyItem.topResult.confidence.toFixed(1)}%`}
                              size="small"
                              sx={{
                                backgroundColor: historyItem.topResult.confidence > 80 ? '#4ECDC420' :
                                  historyItem.topResult.confidence > 50 ? '#FFD93D20' : '#FF6B6B20',
                                color: historyItem.topResult.confidence > 80 ? '#4ECDC4' :
                                  historyItem.topResult.confidence > 50 ? '#FFD93D' : '#FF6B6B',
                                fontWeight: 600
                              }}
                            />
                            {historyItem.topResult.confidence > 80 ? (
                              <CheckCircle sx={{ fontSize: 16, color: '#4ECDC4' }} />
                            ) : historyItem.topResult.confidence > 50 ? (
                              <Warning sx={{ fontSize: 16, color: '#FFD93D' }} />
                            ) : (
                              <ErrorIcon sx={{ fontSize: 16, color: '#FF6B6B' }} />
                            )}
                          </Box>
                          <Typography
                            variant="caption"
                            sx={{
                              color: '#718096',
                              fontStyle: 'italic'
                            }}
                          >
                            {new Date().toLocaleString('zh-CN')}
                          </Typography>
                        </Box>
                      </HistoryCard>
                    </Fade>
                  </Grid>
                ))}
              </Grid>
            ) : (
              <Fade in timeout={2000}>
                <Box
                  sx={{
                    textAlign: 'center',
                    py: 6,
                    background: 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
                    borderRadius: '20px',
                    border: '2px dashed #cbd5e0'
                  }}
                >
                  <History sx={{ fontSize: 60, color: '#cbd5e0', mb: 2 }} />
                  <Typography
                    variant="h6"
                    sx={{
                      color: '#4a5568',
                      fontWeight: 600,
                      mb: 1
                    }}
                  >
                    暂无诊断历史
                  </Typography>
                  <Typography
                    variant="body1"
                    sx={{
                      color: '#718096',
                      fontStyle: 'italic'
                    }}
                  >
                    开始您的第一次AI诊断吧！
                  </Typography>
                </Box>
              </Fade>
            )}
          </Box>
        </Fade>
      </MainPaper>
    </MainContainer>
  );
};

export default PredictionPage;